package com.studio49.exmple.core.filter;

import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.studio49.exmple.common.util.StringUtilsCustom;
import com.studio49.exmple.core.service.appInterface.AppBaseService;
import com.studio49.exmple.entity.web.sys.User;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
//import com.yingxinnet.arvr_mini.common.util.StringUtilsCustom;
import com.studio49.exmple.common.constant.SysConstant;
import com.studio49.exmple.core.entity.pub.JsonResult;

/**
 * 
 * @author chensj
 * @date 2019年2月16日  上午11:54:15
 * @version 1.0
 */
@WebFilter("/appInterface/*")
public class AppInterfaceFilter extends AppBaseService implements Filter {

	private static final Logger LOG = LogManager.getLogger(AppInterfaceFilter.class.getName());

	/** 忽略过滤拦截的url */
	private final String[] ignoreFilterUrlArr = new String[] {
			// uuid登录接口
			"appInterface/appUser/uuidLogin",
			//获取验证码接口
			"appInterface/appUser/getVerificationCode",
			//验证码登录
			"appInterface/appUser/verificationCodeLogin",
			//注册
			"appInterface/appUser/register",
			//手机登录
			"appInterface/appUser/mobileLogin",
			//重置密码
			"appInterface/appUser/resetPassword",
			
			//openId登录
			"appInterface/appUser/openidLogin",
			//获取微信信息
			"appInterface/appUser/getWeChatInfo"
	};

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {
		System.err.println("=========youjiao InterfaceFilter >> doFilter==========");

		HttpServletResponse response = (HttpServletResponse) servletResponse;
		response.setHeader("Access-Control-Allow-Origin", "*");
		response.setHeader("Access-Control-Allow-Methods", "POST");
		response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
		response.setHeader("Access-Control-Max-Age", "3600");
		response.setHeader("Allow", "POST");

		HttpServletRequest request = (HttpServletRequest) servletRequest;
		if (getIsIgnoreFilterUrlArr(request)) {
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		}
		// 判断用户是否登录
		JsonResult jsonResult = new JsonResult();
		try {
			checkUserIsLogin(request);
			filterChain.doFilter(servletRequest, servletResponse);
			return;
		} catch (RuntimeException e) {
			jsonResult = super.setCheckErrMsg(LOG, jsonResult, e);
			responseOutWithJson(response, jsonResult);
			return;
		} catch (Exception e) {
			super.setErrMsg("服务器异常", LOG, jsonResult, e);
			responseOutWithJson(response, jsonResult);
			return;
		}
	}

	/**
	 * response写出结果
	 * 
	 * @param response
	 * @param obj
	 */
	public void responseOutWithJson(HttpServletResponse response, Object obj) {
		OutputStream outputStream = null;
		try {
			String json = JSON.toJSONString(obj);
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			outputStream = response.getOutputStream();
			outputStream.write(json.getBytes("UTF-8"));
			outputStream.flush();
		} catch (IOException e) {
			e.printStackTrace();
			LOG.info("写出数据异常");
		} finally {
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * 判断用户是否是登录状态
	 * 
	 * @throws RuntimeException
	 */
	private void checkUserIsLogin(HttpServletRequest request) throws RuntimeException {
		LOG.warn("start checkUserIsLogin");
		String tokenId = request.getParameter("tokenId");
		String deviceCode = request.getParameter("deviceCode");
		LOG.warn("tokenId=" + tokenId + "deviceCode=" + deviceCode);
		if (StringUtils.isEmpty(tokenId)) {
			throw new RuntimeException(SysConstant.TOKEN_ID_IS_BLANK_CODE + SysConstant.APP_EXCEPTION_DELIMITER
					+ "tokenId不能为空，实际的值:" + tokenId + "！");
		}
//		if (StringUtils.isEmpty(deviceCode)) {
//			throw new RuntimeException(SysConstant.APP_PARAMS_IS_BLANK_CODE + SysConstant.APP_EXCEPTION_DELIMITER
//					+ "deviceCode不能为空，实际的值:" + deviceCode + "！");
//		}

		User appUser = getAppUser(tokenId);
		LOG.warn("用户信息："+JSON.toJSONString(appUser));
		if (appUser == null) {
			throw new RuntimeException(SysConstant.APP_USER_IS_LOGIN + SysConstant.APP_EXCEPTION_DELIMITER + "请先登录");
		}
		//刷新redis时间
		redisComponent.saveData(tokenId, appUser, SysConstant.DEFUALT_REDIS_EXPIRE);
		
		 //判断当前设备是否与用户信息中的设备相同
//		if (!deviceCode.equals(appUser.getDeviceCode())) {
//			throw new RuntimeException(SysConstant.APP_USER_IS_CURRENT + SysConstant.APP_EXCEPTION_DELIMITER + "请先登录");
//		}
	}
	
	/**
	 * 是否忽略过滤拦截的url
	 * 
	 * @return
	 */
	private boolean getIsIgnoreFilterUrlArr(HttpServletRequest request) {
		for (String iaUrl : ignoreFilterUrlArr) {
			if (this.reqUrlEqualsRelativeUrl(request, iaUrl)) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 当前request的url是否和相对路径相同
	 * 
	 * @param relativeUrl
	 * @return
	 */
	private boolean reqUrlEqualsRelativeUrl(HttpServletRequest request, String relativeUrl) {
		if (!StringUtils.isEmpty(relativeUrl)) {
//			String actionPrefix = "/action/"; // springmvc action拦截前缀
			String requestURI = request.getRequestURI();
			String curPath = StringUtilsCustom.formatPath(requestURI.substring(requestURI.indexOf("appInterface")));
			return (relativeUrl).equals(curPath);
		}
		return false;
	}

}
